/*!
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.9.7
 *
 */

(function ($, window, document, undefined) {
    $.fn.lazyload = function (options) {
        var settings = {
            lazyclass: "lazy", //默认class
            callback: null,   //回调
            distance: 200   //默认距离
        };
        $.extend(settings, options);

        function updata() {
            var elements = $("." + settings.lazyclass);
            elements.each(function (i, o) {
                var a=$(o).offset().top;
                var istop = $(window).height() + $(window).scrollTop() > ($(o).offset().top - settings.distance);
                var isleft = $(window).width() + $(window).scrollLeft() > ($(o).offset().left - settings.distance);
                var isbottom = $(o).offset().top + $(o).height() + settings.distance > $(window).scrollTop();
                var isright = $(o).offset().left + $(o).width() + settings.distance > $(window).scrollLeft();
                if (istop && isbottom && isleft && isright) {
                    $(o).appear(settings.lazyclass, settings.callback);
                }
            });
        }

        $(window).bind('scroll', function () {
            updata();
        });
        $(window).bind('resize', function () {
            updata();
        });
        updata();
        return updata;
    };
    $.fn.appear = function (Class, callback) {
        var $that = this;
        if ($that.hasClass(Class)) {
            $that.removeClass(Class);
            var img = new Image();
            img.src = $that.attr("data-img");
            if (img.complete) {
                if ($that[0].nodeName === "IMG") {
                    $that.attr("src", $that.attr("data-img"));

                } else {
                    console.log($that);
                    $that.css("backgroundImage", 'url(' + $that.attr("data-img") + ')');
                }
                if(callback)callback($that);

            } else {
                $(img).bind("load", function () {
                    if ($that[0].nodeName === "IMG") {
                        $that.attr("src", $that.attr("data-img"));

                    } else {
                        console.log($that);
                        $that.css("backgroundImage", 'url(' + $that.attr("data-img") + ')');
                    }
                    if(callback)callback($that);
                });
            }

        }
    };
})(jQuery, window, document);
